﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Provausio.Common.Utility.Extensions;

namespace Provausio.Common.Utility
{
    public class SimpleWebRequest
    {
        private string _url;
        private string _payload;
        public int ResponseCode { get; set; }
        public string ResponseText { get; set; }
        public string ResponseContent { get; set; }
        public WebHeaderCollection ResponseHeaders { get; set; }

        public SimpleWebRequest(string url)
        {
            _url = url;
        }

        /// <summary>
        /// Executes a basic get request for the specified url
        /// </summary>
        public void ExecuteGetRequest()
        {
            GetWebResponse();
        }

        /// <summary>
        /// Executes a basic get request for the specified url and appends a query string to it
        /// </summary>
        /// <param name="query">A collection of key value pairs to be parsed into a url query string</param>
        /// <param name="removeGash">Option to remove trailing "/" from url. Useful for restful services that also accept query strings. Default value = true</param>
        public void ExecuteGetRequest(Dictionary<string,string> query, bool removeGash = true)
        {
            GetWebResponse(query.ToQueryString(), removeGash);
        }

        /// <summary>
        /// Executes POST or PUT request accompanied with a payload
        /// </summary>
        /// <param name="method">Method with which to post to server. Default value = POST</param>
        /// <param name="payload">Payload to be sent to the server (ex. xml or json)</param>
        public void ExecuteRequestWithPayload(string payload, string method = "POST")
        {
            _payload = payload;
            PostWebResponse(method);
        }

        private void GetWebResponse()
        {
            var req = WebRequest.Create(_url);
            req.Method = "GET";
            var response = (HttpWebResponse)req.GetResponse();
            SetResponseValues(response);
        }

        private void GetWebResponse(string query, bool removeGash)
        {
            if (removeGash && _url.EndsWith("/"))
            {
                _url = _url.Substring(0, _url.Length - 1);
            }
            _url += string.Format("?{0}", query);
            GetWebResponse();
        }

        private void PostWebResponse(string method)
        {
            var req = WebRequest.Create(_url);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = method;
            using (var rs = req.GetRequestStream())
            {
                var payloadBytes = Encoding.ASCII.GetBytes(_payload);
                req.ContentLength = payloadBytes.Length;
                rs.Write(payloadBytes, 0, payloadBytes.Length);

                var response = (HttpWebResponse)req.GetResponse();
                SetResponseValues(response);
            }
        }

        private void SetResponseValues(HttpWebResponse response)
        {
            ResponseCode = (int) response.StatusCode;
            ResponseText = response.StatusDescription;
            ResponseHeaders = response.Headers;

            using (var respStream = response.GetResponseStream())
            {
                if (respStream != null)
                    using (var sr = new StreamReader(respStream))
                    {
                        ResponseContent = sr.ReadToEnd();
                    }
            }
        }
    }
}
